const mysql = require('mysql2/promise');
const config = require("../config");
const normalResult = require("../normalResult");


const mysqlService = async (sql, params, transactionConnection) => {
    let connection;
    if (transactionConnection) {
        connection = transactionConnection; // 使用事务连接
    } else {
        const pool = mysql.createPool(config.mysqlConfig);
        connection = await pool.getConnection();
    }
    try {
        const [rows] = await connection.query(sql, params);
        return rows;
    } catch (error) {
        console.error(error);
        throw error;
    } finally {
        if (!transactionConnection) {
            await connection.release(); // 只有非事务连接才主动释放
        }
    }
};

const useTransaction = async (callback) => {
    const pool = mysql.createPool(config.mysqlConfig);
    const connection = await pool.getConnection();
    try {
        await connection.beginTransaction();
        // console.log('Transaction started');
        await callback(connection); // 把 connection 传给 callback
        await connection.commit();
        // console.log('Transaction committed');
    } catch (err) {
        await connection.rollback();
        console.error('Transaction failed:', err);
        throw err; // 向上抛出错误，让调用方处理
    } finally {
        await connection.release(); // 确保连接释放
    }
};


module.exports = {
    mysqlService: mysqlService,
    useTransaction: useTransaction,
    // pool: pool
}
